

#import "ContactListViewController.h"
#import "IDominoAppDelegate.h"
#import "ContactListTableViewCell.h"


static NSString* contact_database_name=@"database.sql";

@implementation  ContactListViewController
@synthesize indexedContactDict;
@synthesize UNIDDict;
@synthesize indexLetters;
@synthesize _tableView;


- (id)init {
	if (self = [super init]) {

		_searchBar=[[UISearchBar alloc] initWithFrame:CGRectMake(0,0,320,40)];
		_searchBar.delegate=self;
		[self.view	addSubview:_searchBar];

		CGRect mainViewBounds = self.view.bounds;
		self._tableView = [[UITableView alloc] initWithFrame:CGRectMake(CGRectGetMinX(mainViewBounds),
																   CGRectGetMinY(mainViewBounds) +40 ,
																   CGRectGetWidth(mainViewBounds),
																   CGRectGetHeight(mainViewBounds)-40+4)
												  style:UITableViewStylePlain];
		_tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);	
        self._tableView.delegate = self;
        self._tableView.dataSource = self;
        self._tableView.rowHeight = 48;
        self._tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
		self._tableView.sectionHeaderHeight =20;
		[self.view addSubview:_tableView];

		UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:	UIBarButtonSystemItemRefresh
																					 target:self action:@selector(refreshAction:)];
	
		self.navigationItem.rightBarButtonItem=refreshItem;

		self.tabBarItem.image=[UIImage imageNamed:@"TabAddressBookView.png"];
		self.tabBarItem.title=NSLocalizedString(@"AddressBook", @"AddressBook Title");
		indexedContactDict = [[NSMutableDictionary alloc] init];
		UNIDDict = [[NSMutableDictionary alloc] init];
		isPersonal=YES;
		self.hidesBottomBarWhenPushed=NO;
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		databasePath = [[documentsDirectory stringByAppendingPathComponent:contact_database_name] retain];
		
		NSArray *segmentTextContent = [NSArray arrayWithObjects:
									   NSLocalizedString(@"Personal", @""),
									   NSLocalizedString(@"Directory", @""),
									   NSLocalizedString(@"IPhone", @""),
									   nil];
		UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
		segmentedControl.selectedSegmentIndex = 0;
		segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
		segmentedControl.frame = CGRectMake(0, 0, 400, 30);
		[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
	
		self.navigationItem.titleView = segmentedControl;
		[segmentedControl release];
	
	}
	return self;
}

- (void)segmentAction:(id)sender
{
	UISegmentedControl* segCtl = sender;
	// the segmented control was clicked, handle it here 
	int selection=[segCtl selectedSegmentIndex];
	if(selection==0)
		isPersonal=YES;
	else if(selection==1)
		isPersonal=NO;
	else if(selection==2){
		IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
		ABPeoplePickerNavigationController* IPhoneContacts=[[ABPeoplePickerNavigationController alloc] init];
		IPhoneContacts.peoplePickerDelegate=self;
		[appDelegate.contactNavigationController presentModalViewController:IPhoneContacts animated:YES];
		[IPhoneContacts release];
	}
	_searchBar.text=@"";
	[self getNameWithKeyword:nil ];
}

- (void)refreshAction:(id)sender
{	
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	[appDelegate updateContacts:isPersonal];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	
	if([indexLetters count] == 0 )
		return 1;
	else
		return [indexLetters count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([indexLetters count]==0) {
        return 1;
    }
	NSString* prefix=[indexLetters objectAtIndex:section];
	NSArray* array=[indexedContactDict objectForKey:prefix];
	return [array count];	
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if([indexLetters count]== 0){
		return nil;
	}
	return [indexLetters objectAtIndex:section];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{	
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	if([indexLetters count]==0)
		return ;
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSString* prefix=[indexLetters objectAtIndex:indexPath.section];
	NSArray* array=[indexedContactDict objectForKey:prefix];
	
	if(isPersonal==YES)
		[appDelegate showPersonInfo:[self getPersonByUNIDInPersonal:[UNIDDict objectForKey:[array objectAtIndex:indexPath.row]]]];
	else
		[appDelegate showDirectoryPersonInfo:[self getPersonByUNIDInDirectory:[UNIDDict objectForKey:[array objectAtIndex:indexPath.row]]]];
	return ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	static NSString *MyIdentifier = @"MyIdentifier";
    
  //	ContactListTableViewCell *cell = (ContactListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	UITableViewCell * cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	if (cell == nil) {
		//cell = [[[ContactListTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"DefaultTableViewCell"] autorelease];
	}
    
    // Set up the cell.
    
	if (  [indexLetters count]==0 ) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"DefaultTableViewCell"] autorelease];
		cell.textLabel.text=NSLocalizedString(@"N/A", @"Not Available");
		cell.textLabel.textColor = [UIColor colorWithWhite:0.5 alpha:0.5];
		cell.accessoryType = UITableViewCellAccessoryNone;
		cell.selectionStyle=UITableViewCellSelectionStyleNone;
		return cell;
	}
	NSString* prefix=[indexLetters objectAtIndex:indexPath.section];
	NSArray* array=[indexedContactDict objectForKey:prefix];
	cell.textLabel.text=[array objectAtIndex:indexPath.row];
    
	return cell;
}


- (void)dealloc {
	[_searchBar release];
	[super dealloc];
}





- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
	// Return the index for the given section title
	return [indexLetters indexOfObject:title];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {	
	return indexLetters;	
}



- (void)initDisplayList{
	[self getNameWithKeyword:nil];
}

static sqlite3_stmt *query_statement = nil;

- (void)getNameWithKeyword:(NSString*)keyword  {
	NSString* firstName;
	NSString* lastName;
	NSString* company;
	NSString* UNID;
	[indexedContactDict removeAllObjects];
		[UNIDDict removeAllObjects];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
	}
	char* sql;
	if(keyword!=nil){
		if(isPersonal)
			sql = "SELECT UNID, firstName, lastName, organization FROM personal WHERE firstName like ? or lastName like ?";
		else
			sql = "SELECT UNID, firstName, lastName FROM directory WHERE firstName like ? or lastName like ?";
	}else{

		if(isPersonal)
			sql="SELECT UNID,firstName, lastName, organization FROM personal";
		else
			sql="SELECT UNID,firstName, lastName FROM directory";
	}
	if (sqlite3_prepare_v2(database, sql, -1, &query_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	// For this query, we bind the primary key to the first (and only) placeholder in the statement.
	// Note that the parameters are numbered from 1, not from 0.
	//sqlite3_bind_text(query_statement, 1, [tableName UTF8String], -1, SQLITE_TRANSIENT);
	if(keyword!=nil){
		NSRange range=[keyword rangeOfString:@","];
		if(range.location==NSNotFound){
			sqlite3_bind_text(query_statement, 1, [keyword UTF8String], -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(query_statement, 2, [keyword UTF8String], -1, SQLITE_TRANSIENT);
		}else{
			sqlite3_bind_text(query_statement, 1, [[keyword substringToIndex:range.location] UTF8String], -1, SQLITE_TRANSIENT);
			if([keyword rangeOfString:@", "].location !=NSNotFound)
				sqlite3_bind_text(query_statement, 2, [[keyword substringFromIndex:range.location+2] UTF8String], -1, SQLITE_TRANSIENT);
			else
				sqlite3_bind_text(query_statement, 2, [[keyword substringFromIndex:range.location+1] UTF8String], -1, SQLITE_TRANSIENT);
		}
	}
	NSMutableArray* missLastNameArray= [[NSMutableArray alloc] init];
	while (sqlite3_step(query_statement) == SQLITE_ROW) {
		UNID= [NSString stringWithUTF8String:(char *)sqlite3_column_text(query_statement, 0)];
		firstName= [NSString stringWithUTF8String:(char *)sqlite3_column_text(query_statement, 1)];
		lastName= [NSString stringWithUTF8String:(char *)sqlite3_column_text(query_statement, 2)];
		if(isPersonal)
			company= [NSString stringWithUTF8String:(char *)sqlite3_column_text(query_statement, 3)];
		if(![lastName isEqualToString:@""] && lastName!=nil){
			NSString *firstLetter = [[lastName substringToIndex:1] uppercaseString];
			NSMutableArray *indexArray = [indexedContactDict objectForKey:firstLetter];
			if (indexArray == nil) {
				indexArray = [[NSMutableArray alloc] init];
				[indexedContactDict setObject:indexArray forKey:firstLetter];
				[indexArray release];
			}
			NSString* display=[NSString stringWithFormat:@"%@, %@", lastName, firstName];
			[indexArray addObject:display];
			[UNIDDict setObject:UNID forKey:display];
		}else if(![firstName isEqualToString:@""] && firstName!=nil){
			[missLastNameArray addObject:firstName];
			[UNIDDict setObject:UNID forKey:firstName];
		}
		else if(isPersonal){
			[missLastNameArray addObject:company];
			[UNIDDict setObject:UNID forKey:company];
		}
		if([missLastNameArray count]!=0)
			[indexedContactDict setObject:missLastNameArray forKey:@"#"];
	} 
	[missLastNameArray release];
	// Reset the statement for future reuse.
	sqlite3_finalize(query_statement);
	
	if (sqlite3_close(database) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));
	}	
	self.indexLetters = [[indexedContactDict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
	[self._tableView reloadData];
}

#pragma mark searchBarDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	if([searchText isEqualToString:@""]){
		[searchBar resignFirstResponder];
		[self getNameWithKeyword:nil ];
	}
	else{
		[self getNameWithKeyword:[NSString stringWithFormat:@"%%%@%%",searchText] ];
	}
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	[searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	searchBar.text=nil; 
}

#pragma mark SQLInteraction
static sqlite3_stmt *retrieve_statement = nil;

- (Person*)getPersonByUNIDInPersonal:(NSString*)UNID {
	
	Person* person=[[Person alloc] init];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
	}
	const char *sql = "SELECT * FROM personal WHERE UNID=?";
	if (sqlite3_prepare_v2(database, sql, -1, &retrieve_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	// For this query, we bind the primary key to the first (and only) placeholder in the statement.
	// Note that the parameters are numbered from 1, not from 0.
	sqlite3_bind_text(retrieve_statement, 1, [UNID UTF8String], -1, SQLITE_TRANSIENT);
	while (sqlite3_step(retrieve_statement) == SQLITE_ROW) {
		[person setUNID:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 0)]];
		[person setPrefix:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 1)]];
		[person setFirstName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 2)]];
		[person setMiddleName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 3)]];
		[person setLastName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 4)]];
		[person setSuffix:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 5)]];
		[person setJobTitle:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 6)]];
		[person setDepartment:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 7)]];
		[person setCompany:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 8)]];
		[person setEmail:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 9)]];
		[person setStreet:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 10)]];
		[person setCity:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 11)]];
		[person setState:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 12)]];
		[person setZip:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 13)]];
		[person setCountry:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 14)]];
		[person setMobile:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 15)]];
		[person setWorkPhone:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 16)]];
		[person setWorkFax:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 17)]];
		[person setWorkPager:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 18)]];
		[person setHomeFax:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 19)]];
		[person setUpdatedInDatabase:[[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 20)] boolValue]];
	} 
	// Reset the statement for future reuse.
	sqlite3_finalize(retrieve_statement);
	
	if (sqlite3_close(database) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));
	}	
	return [person autorelease];
}

- (Person*)getPersonByUNIDInDirectory:(NSString*)UNID {	
	Person* person=[[Person alloc] init];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
	}
	const char *sql = "SELECT firstName, lastName, email, phoneNumber, updated FROM directory WHERE UNID=?";
	if (sqlite3_prepare_v2(database, sql, -1, &retrieve_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	// For this query, we bind the primary key to the first (and only) placeholder in the statement.
	// Note that the parameters are numbered from 1, not from 0.
	sqlite3_bind_text(retrieve_statement, 1, [UNID UTF8String], -1, SQLITE_TRANSIENT);
	while (sqlite3_step(retrieve_statement) == SQLITE_ROW) {
		[person setUNID:UNID];
		[person setFirstName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 0)]];
		[person setLastName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 1)]];
		[person setUpdatedInDatabase:[[NSString stringWithUTF8String:(char *)sqlite3_column_text(retrieve_statement, 4)] boolValue]];
		char* string=(char *)sqlite3_column_text(retrieve_statement, 2);
		if(string!=nil)
			[person setEmail:[NSString stringWithUTF8String:string]];
		string=(char *)sqlite3_column_text(retrieve_statement, 3);
		if(string!=nil)
			[person setWorkPhone:[NSString stringWithUTF8String:string]];

	} 
	// Reset the statement for future reuse.
	sqlite3_finalize(retrieve_statement);
	
	if (sqlite3_close(database) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));
	}	
	
	return [person autorelease];
}




- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
	return YES;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
	return YES;
}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	[appDelegate.contactNavigationController dismissModalViewControllerAnimated:YES];
}

- (UITableView*)tableView
{
	return _tableView;
}


@end

